<template>

  <com-page class="u-wrap" :class="{ 'has-apply-footer': fromApply }">
    
	<view class="com-flex">
		<u-icon class="com-pl-13" @click="$utils.router({ type: 'back' })"
		                    name="arrow-left"
		                    size="20"
							color="#303133"
		                ></u-icon>
		<view class="u-search-box com-flex-1">
		  <view class="u-search-inner">
		    <u-icon name="search"
		            color="#909399"
		            :size="28" />
		    <text class="u-search-text">搜索</text>
		  </view>
		</view>
	</view>
	
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <text>加载中...</text>
    </view>
    
    <view class="u-menu-wrap" v-else>
      <scroll-view scroll-y
                   scroll-with-animation
                   class="u-tab-view menu-scroll-view"
                   :scroll-top="scrollTop"
                   :scroll-into-view="itemId">
        <view v-for="(item, index) in tabbar"
              :key="index"
              class="u-tab-item"
              :class="[current == index ? 'u-tab-item-active' : '']"
              @tap.stop="swichMenu(index)">
          <text class="u-line-1">{{ item.name }}</text>
        </view>
      </scroll-view>
      <scroll-view :scroll-top="scrollRightTop"
                   scroll-y
                   scroll-with-animation
                   class="right-box"
                   @scroll="rightScroll">
        <view class="page-view">
          <view class="class-item"
                :id="'item' + index"
                v-for="(item, index) in tabbar"
                :key="index">
            <view class="item-title">
              <text>{{ item.name }}</text>
            </view>
            <view class="item-container">
              <view class="thumb-box"
                    v-for="(product, index1) in item.products"
                    :key="index1"
                    :class="{ 'selected': fromApply && isProductSelected(product.id) }"
                    @click="onProductClick(product)">
                <view class="product-wrapper">
                  <image class="item-menu-image"
                         :src="product.pic"
                         mode="aspectFill" />
                  <!-- 选中状态指示器 -->
                  <view v-if="fromApply && isProductSelected(product.id)" class="selected-indicator">
                    <text class="selected-icon" v-if="getProductSelectedCount(product.id) === 1">✓</text>
                    <text class="selected-count" v-else>{{ getProductSelectedCount(product.id) }}</text>
                  </view>
                </view>
                <view class="item-menu-name">{{ product.name }}</view>
                <view class="item-price">¥{{ product.price }}</view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 报名流程底部按钮 -->
    <view v-if="fromApply" class="apply-footer">
      <view class="selected-info">
        <text v-if="selectedCount > 0">已选择 {{ selectedCount }} 件商品</text>
        <text v-else>未选择商品（可选）</text>
      </view>
      <view class="apply-buttons">
        <button class="btn btn-secondary" @click="onPrevStep">上一步</button>
        <button class="btn btn-primary" @click="onNextStep">完成报名</button>
      </view>
    </view>

    <!-- 规格选择弹窗 -->
    <view v-if="showSpecModal" class="spec-modal-overlay" @click="closeSpecModal">
      <view class="spec-modal" @click.stop="">
        <!-- 商品信息 -->
        <view class="spec-product-info">
          <image :src="currentProduct.pic" class="spec-product-image" mode="aspectFill" />
          <view class="spec-product-details">
            <view class="spec-product-name">{{ currentProduct.name }}</view>
            <view class="spec-product-price">¥{{ currentPrice }}</view>
            <view class="spec-product-stock">库存：{{ currentStock }} 件</view>
          </view>
          <view class="spec-close-btn" @click="closeSpecModal">×</view>
        </view>

        <!-- 规格选择 -->
        <view class="spec-attrs" v-if="productAttrs.length > 0">
          <view v-for="(attr, index) in productAttrs" :key="index" class="spec-attr-group">
            <view class="spec-attr-name">{{ attr.name }}</view>
            <view class="spec-attr-options">
              <view 
                v-for="(option, optionIndex) in attr.options" 
                :key="optionIndex"
                v-if="option.name"
                class="spec-attr-option"
                :class="{ active: selectedSpecs[attr.name] === option.name }"
                @click="selectSpec(attr.name, option.name)"
              >
                {{ option.name }}
              </view>
            </view>
          </view>
        </view>

        <!-- 数量选择 -->
        <view class="spec-quantity">
          <view class="spec-quantity-label">数量</view>
          <view class="spec-quantity-control">
            <view class="quantity-btn" :class="{ disabled: quantity <= 1 }" @click="decreaseQuantity">-</view>
            <view class="quantity-input">{{ quantity }}</view>
            <view class="quantity-btn" :class="{ disabled: quantity >= currentStock }" @click="increaseQuantity">+</view>
          </view>
        </view>

        <!-- 确认按钮 -->
        <view class="spec-confirm">
          <view v-if="isCurrentSkuSelected" class="spec-buttons">
            <button class="spec-delete-btn" @click="removeProductFromSelection">
              删除商品
            </button>
            <button class="spec-confirm-btn" :class="{ disabled: !matchedSku }" @click="confirmSpecSelection">
              确认修改
            </button>
          </view>
          <button v-else class="spec-confirm-btn" :class="{ disabled: !matchedSku }" @click="confirmSpecSelection">
            确认选择
          </button>
        </view>
      </view>
    </view>
  </com-page>
</template>
<script>
export default {
  name: 'App-Category',
  data() {
    return {
      scrollTop: 0, //tab标题的滚动条位置
      oldScrollTop: 0,
      current: 0, // 预设当前项的值
      menuHeight: 0, // 左边菜单的高度
      menuItemHeight: 0, // 左边菜单item的高度
      itemId: '', // 栏目右边scroll-view用于滚动的id
      tabbar: [], // 商品分类数据
      menuItemPos: [],
      arr: [],
      scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
      timer: null, // 定时器
      evtId: null, // 赛事ID
      loading: false, // 加载状态
      fromApply: false, // 是否来自报名流程
      selectedProducts: [], // 选中的商品列表
      showSpecModal: false, // 显示规格选择弹窗
      currentProduct: null, // 当前选择的商品
      selectedSpecs: {}, // 选中的规格
      selectedSku: null, // 选中的SKU
      quantity: 1, // 选择数量
    }
  },
  computed: {
    selectedCount() {
      return this.selectedProducts.length;
    },
    isProductSelected() {
      return (productId) => {
        return this.selectedProducts.some(item => item.id === productId);
      }
    },
    // 获取商品的选中数量（所有SKU数量之和）
    getProductSelectedCount() {
      return (productId) => {
        const productItems = this.selectedProducts.filter(item => item.id === productId);
        return productItems.reduce((sum, item) => sum + (item.quantity || 1), 0);
      }
    },
    // 当前商品的规格属性
    productAttrs() {
      if (!this.currentProduct || !this.currentProduct.productAttr) return [];
      try {
        return JSON.parse(this.currentProduct.productAttr);
      } catch (error) {
        return [];
      }
    },
    // 根据选中规格找到对应的SKU
    matchedSku() {
      if (!this.currentProduct || !this.currentProduct.skus) return null;
      const selectedSpecsStr = JSON.stringify(this.selectedSpecs);
      return this.currentProduct.skus.find(sku => sku.spData === selectedSpecsStr);
    },
    // 当前选择的价格
    currentPrice() {
      if (this.matchedSku) {
        return this.matchedSku.price;
      }
      return this.currentProduct ? this.currentProduct.price : 0;
    },
    // 当前库存
    currentStock() {
      if (this.matchedSku) {
        return this.matchedSku.stock;
      }
      return 999; // 默认库存
    },
    // 当前SKU是否已选中
    isCurrentSkuSelected() {
      if (!this.currentProduct || !this.matchedSku) return false;
      return this.selectedProducts.some(item => 
        item.id === this.currentProduct.id && 
        item.skuId === this.matchedSku.id
      );
    }
  },
  async onLoad(options) {
    console.log('商品页面onLoad接收到的参数:', options);
    
    // 获取赛事ID，优先从参数获取，其次从缓存获取
    this.evtId = options.evtId || uni.getStorageSync('currentEventId');
    
    // 检测是否来自报名流程
    if (options && options.fromApply === 'true') {
      this.fromApply = true;
      console.log('检测到来自报名流程，设置fromApply为true');
      uni.setNavigationBarTitle({
        title: this.$t('pages_category_category_msg_43d1e28a')
      });
    }
    
    console.log('商品页面获取到的赛事ID:', this.evtId);
    console.log('商品页面fromApply状态:', this.fromApply);
    
    if (this.evtId) {
      await this.loadProductCategories();
    } else {
      uni.showModal({
        title: this.$t('pages_category_category_text_02d9819d'),
        content: '缺少赛事信息，请返回首页重新选择赛事',
        showCancel: false,
        success: () => {
          uni.switchTab({
            url: '/pages/index/index'
          });
        }
      });
    }
  },
  onReady() {
    this.getMenuItemTop()
  },
  methods: {
    // 加载商品分类
    async loadProductCategories() {
      try {
        this.loading = true;
        const categories = await this.$api.event.productCategory();
        
        if (categories && categories.length > 0) {
          // 为每个分类加载商品列表
          this.tabbar = await Promise.all(categories.map(async (category) => {
            const products = await this.loadProductsByCategory(category.id);
            return {
              id: category.id,
              name: category.name,
              products: products || []
            };
          }));
        } else {
          uni.showToast({
            title: this.$t('pages_category_category_msg_b2de9f3a'),
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载商品分类失败:', error);
        uni.showToast({
          title: this.$t('pages_category_category_msg_866b795e'),
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 根据分类ID加载商品列表
    async loadProductsByCategory(categoryId) {
      try {
        const products = await this.$api.event.productList({
          categoryId: categoryId,
          evtId: this.evtId
        });
        return products;
      } catch (error) {
        console.error('加载商品列表失败:', error);
        return [];
      }
    },

    // 点击商品
    onProductClick(product) {
		this.$utils.router({
		        url: `/pages/product/detail/detail?id=${product.id}`
		      })
      // if (!product || !product.id) {
      //   uni.showToast({
      //     title: this.$t('pages_category_category_msg_e49fa262'),
      //     icon: 'none'
      //   });
      //   return;
      // }

      // if (this.fromApply) {
      //   // 报名流程中，检查是否有SKUs需要选择规格
      //   if (product.skus && product.skus.length > 0) {
      //     // 有SKUs，显示规格选择（无论是否已选中）
      //     this.showSpecSelection(product);
      //   } else {
      //     // 没有SKUs，直接切换选择状态
      //     this.toggleProductSelection(product);
      //   }
      // } else {
      //   // 非报名流程，显示提示
      //   uni.showToast({
      //     title: `选择了商品：${product.name}`,
      //     icon: 'success'
      //   });
      // }
    },

    // 切换商品选择状态
    toggleProductSelection(product) {
      const index = this.selectedProducts.findIndex(item => item.id === product.id);
      if (index > -1) {
        // 已选中，取消选择
        this.selectedProducts.splice(index, 1);
        uni.showToast({
          title: `已取消选择：${product.name}`,
          icon: 'none'
        });
      } else {
        // 未选中，添加选择，包含报名接口所需的字段
        this.selectedProducts.push({
          id: product.id,
          name: product.name,
          price: product.price,
          pic: product.pic,
          skuId: null,
          specs: {},
          quantity: 1,
          stock: 999,
          // 报名接口需要的额外字段
          outSkuId: null,
          outProductId: product.outProductId || product.id.toString(),
          brandName: product.brandName || '',
          categoryName: product.categoryName || ''
        });
        uni.showToast({
          title: `已选择：${product.name}`,
          icon: 'success'
        });
      }
    },

    // 显示规格选择弹窗
    showSpecSelection(product) {
      this.currentProduct = product;
      this.selectedSpecs = {};
      this.selectedSku = null;
      this.quantity = 1;
      this.showSpecModal = true;

      // 检查是否已经选择过该商品的某个SKU
      const existingProduct = this.selectedProducts.find(item => item.id === product.id);
      
      if (existingProduct) {
        // 如果已选择过，使用已选择的规格和数量
        this.selectedSpecs = { ...existingProduct.specs };
        this.quantity = existingProduct.quantity;
      } else {
        // 如果未选择过，初始化规格选择（默认选择第一个有效选项）
        if (this.productAttrs.length > 0) {
          this.productAttrs.forEach(attr => {
            if (attr.options && attr.options.length > 0) {
              const validOption = attr.options.find(option => option.name);
              if (validOption) {
                this.$set(this.selectedSpecs, attr.name, validOption.name);
              }
            }
          });
        }
      }
    },

    // 关闭规格选择弹窗
    closeSpecModal() {
      this.showSpecModal = false;
      this.currentProduct = null;
      this.selectedSpecs = {};
      this.selectedSku = null;
      this.quantity = 1;
    },

    // 选择规格
    selectSpec(attrName, optionName) {
      this.$set(this.selectedSpecs, attrName, optionName);
    },

    // 增加数量
    increaseQuantity() {
      if (this.quantity < this.currentStock) {
        this.quantity++;
      }
    },

    // 减少数量
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--;
      }
    },

    // 确认选择规格
    confirmSpecSelection() {
      if (!this.matchedSku) {
        uni.showToast({
          title: this.$t('pages_category_category_desc_7d66143e'),
          icon: 'none'
        });
        return;
      }

      // 构造选中的商品信息，包含报名接口所需的字段
      const selectedProduct = {
        id: this.currentProduct.id,
        name: this.currentProduct.name,
        price: this.currentPrice,
        pic: this.currentProduct.pic,
        skuId: this.matchedSku.id,
        specs: { ...this.selectedSpecs },
        quantity: this.quantity,
        stock: this.currentStock,
        // 报名接口需要的额外字段
        outSkuId: this.matchedSku.outSkuId || null,
        outProductId: this.currentProduct.outProductId || this.currentProduct.id.toString(),
        brandName: this.currentProduct.brandName || '',
        categoryName: this.currentProduct.categoryName || ''
      };

      // 检查是否已经选择了同样规格的商品
      const existIndex = this.selectedProducts.findIndex(item => 
        item.id === selectedProduct.id && 
        item.skuId === selectedProduct.skuId
      );

      if (existIndex > -1) {
        // 已存在，更新数量
        this.selectedProducts[existIndex].quantity = selectedProduct.quantity;
        uni.showToast({
          title: `已更新：${selectedProduct.name}`,
          icon: 'success'
        });
      } else {
        // 不存在，添加新商品
        this.selectedProducts.push(selectedProduct);
        uni.showToast({
          title: `已添加：${selectedProduct.name}`,
          icon: 'success'
        });
      }

      this.closeSpecModal();
    },

    // 从选择列表中删除商品
    removeProductFromSelection() {
      if (!this.matchedSku) return;
      
      const existIndex = this.selectedProducts.findIndex(item => 
        item.id === this.currentProduct.id && 
        item.skuId === this.matchedSku.id
      );

      if (existIndex > -1) {
        const productName = this.selectedProducts[existIndex].name;
        this.selectedProducts.splice(existIndex, 1);
        uni.showToast({
          title: `已删除：${productName}`,
          icon: 'none'
        });
        this.closeSpecModal();
      }
    },

    // 上一步：返回用户信息页面
    onPrevStep() {
      uni.navigateBack();
    },

    // 下一步：完成报名
    async onNextStep() {

      const modalContent = this.selectedProducts.length > 0 
        ? `您已选择 ${this.selectedProducts.length} 项商品，确认完成报名吗？`
        : '确认完成报名吗？';
      
      uni.showModal({
        title: this.$t('pages_category_category_msg_5b7c2c3d'),
        content: modalContent,
        success: async (res) => {
          if (res.confirm) {
            try {
              // 构造订单数据，按照接口要求的skus格式
              const orderData = {
                evtId: this.evtId,
                skus: this.selectedProducts.length > 0 ? this.selectedProducts.map(product => {
                  // 构造 skuSpec 字符串
                  let skuSpec = this.$t('pages_category_category_msg_064eb9e8');
                  if (product.specs && Object.keys(product.specs).length > 0) {
                    skuSpec = Object.entries(product.specs)
                      .map(([key, value]) => `${key}: ${value}`)
                      .join(', ');
                  }

                  return {
                    productId: product.id,
                    skuId: product.skuId || null,
                    productName: product.name,
                    price: product.price,
                    skuSpec: skuSpec,
                    quantity: product.quantity || 1,
                    outSkuId: product.outSkuId || null,
                    outProductId: product.outProductId || product.id.toString(),
                    brandName: product.brandName || '',
                    categoryName: product.categoryName || '',
                    pic: product.pic || null
                  };
                }) : []
              };

              console.log('创建订单数据:', orderData);
              
              // 调用创建订单接口
              await this.$api.event.create(orderData);
              
              uni.showToast({
                title: '报名成功！',
                icon: 'success',
                duration: 2000,
                success: () => {
                  setTimeout(() => {
                    uni.switchTab({
                      url: '/pages/index/index'
                    });
                  }, 2000);
                }
              });
            } catch (error) {
              console.error('创建订单失败:', error);
              uni.showToast({
                title: '报名失败，请重试',
                icon: 'none'
              });
            }
          }
        }
      });
    },

    // 点击左边的栏目切换
    async swichMenu(index) {
      if (this.arr.length == 0) {
        await this.getMenuItemTop()
      }
      if (index == this.current) return
      this.scrollRightTop = this.oldScrollTop
      this.$nextTick(function () {
        this.scrollRightTop = this.arr[index]
        this.current = index
        this.leftMenuStatus(index)
      })
    },
    // 获取一个目标元素的高度
    getElRect(elClass, dataVal) {
      new Promise((resolve) => {
        const query = uni.createSelectorQuery().in(this)
        query
          .select('.' + elClass)
          .fields(
            {
              size: true,
            },
            (res) => {
              // 如果节点尚未生成，res值为null，循环调用执行
              if (!res) {
                setTimeout(() => {
                  this.getElRect(elClass)
                }, 10)
                return
              }
              this[dataVal] = res.height
              resolve()
            }
          )
          .exec()
      })
    },
    // 观测元素相交状态
    async observer() {
      this.tabbar.map((val, index) => {
        let observer = uni.createIntersectionObserver(this)
        // 检测右边scroll-view的id为itemxx的元素与right-box的相交状态
        // 如果跟.right-box底部相交，就动态设置左边栏目的活动状态
        observer
          .relativeTo('.right-box', {
            top: 0,
          })
          .observe('#item' + index, (res) => {
            if (res.intersectionRatio > 0) {
              let id = res.id.substring(4)
              this.leftMenuStatus(id)
            }
          })
      })
    },
    // 设置左边菜单的滚动状态
    async leftMenuStatus(index) {
      this.current = index
      // 如果为0，意味着尚未初始化
      if (this.menuHeight == 0 || this.menuItemHeight == 0) {
        await this.getElRect('menu-scroll-view', 'menuHeight')
        await this.getElRect('u-tab-item', 'menuItemHeight')
      }
      // 将菜单活动item垂直居中
      this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2
    },
    // 获取右边菜单每个item到顶部的距离
    getMenuItemTop() {
      new Promise((resolve) => {
        let selectorQuery = uni.createSelectorQuery()
        selectorQuery
          .selectAll('.class-item')
          .boundingClientRect((rects) => {
            // 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
            if (!rects.length) {
              setTimeout(() => {
                this.getMenuItemTop()
              }, 10)
              return
            }
            rects.forEach((rect) => {
              // 这里减去rects[0].top，是因为第一项顶部可能不是贴到导航栏(比如有个搜索框的情况)
              this.arr.push(rect.top - rects[0].top)
              resolve()
            })
          })
          .exec()
      })
    },
    // 右边菜单滚动
    async rightScroll(e) {
      this.oldScrollTop = e.detail.scrollTop
      if (this.arr.length == 0) {
        await this.getMenuItemTop()
      }
      if (this.timer) return
      if (!this.menuHeight) {
        await this.getElRect('menu-scroll-view', 'menuHeight')
      }
      setTimeout(() => {
        // 节流
        this.timer = null
        // scrollHeight为右边菜单垂直中点位置
        let scrollHeight = e.detail.scrollTop + this.menuHeight / 2
        for (let i = 0; i < this.arr.length; i++) {
          let height1 = this.arr[i]
          let height2 = this.arr[i + 1]
          // 如果不存在height2，意味着数据循环已经到了最后一个，设置左边菜单为最后一项即可
          if (!height2 || (scrollHeight >= height1 && scrollHeight < height2)) {
            this.leftMenuStatus(i)
            return
          }
        }
      }, 10)
    },
  },
}
</script>

<style lang="scss" scoped>
.u-wrap {
  height: calc(100vh);
  /* #ifdef H5 */
  height: calc(100vh - var(--window-top));
  /* #endif */
  display: flex;
  flex-direction: column;
}

.u-search-box {
  /* #ifdef APP-PLUS | H5 */
  // position: fixed;
  // top: 0;
  // right: 0;
  // left: 0;
  // background-color: #f8f8f8;
  z-index: 999;
  padding: 18rpx 30rpx;
  /* #endif */
  /* #ifdef MP */
  padding: calc(2px + var(--status-bar-height)) 30rpx 18rpx;
  width: 520rpx;
  /* #endif */
}

.u-menu-wrap {
  flex: 1;
  display: flex;
  overflow: hidden;
  /* #ifdef APP-PLUS | H5 */
  margin-top: 24rpx;
  /* #endif */
}

.u-search-inner {
  background-color: rgb(234, 234, 234);
  border-radius: 100rpx;
  display: flex;
  align-items: center;
  padding: 12rpx 16rpx;
}

.u-search-text {
  font-size: 26rpx;
  color: $u-tips-color;
  margin-left: 10rpx;
}

.u-tab-view {
  width: 200rpx;
  height: 100%;
}

.u-tab-item {
  height: 110rpx;
  background: #f6f6f6;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
  color: #444;
  font-weight: 400;
  line-height: 1;
}

.u-tab-item-active {
  position: relative;
  color: #000;
  font-size: 30rpx;
  font-weight: 600;
  background: #fff;
}

.u-tab-item-active::before {
  content: '';
  position: absolute;
  border-left: 4px solid $com-color-primary;
  height: 32rpx;
  left: 0;
  top: 39rpx;
}

.u-tab-view {
  height: 100%;
}

.right-box {
  background-color: rgb(250, 250, 250);
}

.page-view {
  padding: 16rpx;
}

.class-item {
  margin-bottom: 30rpx;
  background-color: #fff;
  padding: 16rpx;
  border-radius: 8rpx;
}

.class-item:last-child {
  min-height: 100vh;
}

.item-title {
  font-size: 26rpx;
  color: $u-main-color;
  font-weight: bold;
}

.item-menu-name {
  font-weight: normal;
  font-size: 24rpx;
  color: $u-main-color;
  margin-top: 8rpx;
  text-align: center;
}

.item-price {
  font-size: 28rpx;
  color: #ff6b35;
  font-weight: 600;
  margin-top: 4rpx;
  text-align: center;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;
  font-size: 28rpx;
  color: #666;
}

.item-container {
  display: flex;
  flex-wrap: wrap;
}

.thumb-box {
  width: 33.333333%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  margin-top: 20rpx;
  cursor: pointer;
  transition: transform 0.2s ease;
  
  &:hover {
    transform: scale(1.05);
  }
}

.item-menu-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
}

.thumb-box {
  &.selected {
    transform: scale(0.95);
    opacity: 0.8;
    
    .product-wrapper {
      position: relative;
      border: 2px solid #007aff;
      border-radius: 12rpx;
      padding: 4rpx;
    }
  }
}

.product-wrapper {
  position: relative;
  transition: all 0.3s ease;
}

.selected-indicator {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  width: 32rpx;
  height: 32rpx;
  background: #007aff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #fff;

  .selected-icon {
    color: white;
    font-size: 20rpx;
    font-weight: bold;
  }

  .selected-count {
    color: white;
    font-size: 18rpx;
    font-weight: bold;
  }
}

// 有底部按钮时的页面内边距
.has-apply-footer {
  padding-bottom: 200rpx;
}

// 报名流程底部按钮
.apply-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  padding: 24rpx;
  z-index: 100;

  .selected-info {
    text-align: center;
    margin-bottom: 16rpx;
    font-size: 28rpx;
    color: #666;
  }

  .apply-buttons {
    display: flex;
    gap: 24rpx;

    .btn {
      flex: 1;
      height: 88rpx;
      border-radius: 44rpx;
      font-size: 32rpx;
      font-weight: 500;
      border: none;

      &.btn-secondary {
        background: #f5f5f5;
        color: #666;
      }

      &.btn-primary {
        background: #007aff;
        color: white;
      }
    }
  }
}

// 规格选择弹窗
.spec-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 1000;
}

.spec-modal {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  width: 100%;
  max-height: 80vh;
  overflow-y: auto;
  padding: 32rpx;
  position: relative;
}

.spec-product-info {
  display: flex;
  align-items: flex-start;
  margin-bottom: 32rpx;
  position: relative;

  .spec-product-image {
    width: 120rpx;
    height: 120rpx;
    border-radius: 8rpx;
    margin-right: 16rpx;
  }

  .spec-product-details {
    flex: 1;

    .spec-product-name {
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
      margin-bottom: 8rpx;
      line-height: 1.4;
    }

    .spec-product-price {
      font-size: 36rpx;
      color: #ff6b35;
      font-weight: 600;
      margin-bottom: 8rpx;
    }

    .spec-product-stock {
      font-size: 26rpx;
      color: #666;
    }
  }

  .spec-close-btn {
    position: absolute;
    top: -8rpx;
    right: -8rpx;
    width: 48rpx;
    height: 48rpx;
    background: #f5f5f5;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    color: #666;
    font-weight: bold;
  }
}

.spec-attrs {
  margin-bottom: 32rpx;

  .spec-attr-group {
    margin-bottom: 24rpx;

    .spec-attr-name {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 16rpx;
      font-weight: 500;
    }

    .spec-attr-options {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;
    }

    .spec-attr-option {
      padding: 16rpx 24rpx;
      border: 1px solid #ddd;
      border-radius: 8rpx;
      font-size: 26rpx;
      color: #333;
      background: #fff;
      min-width: 80rpx;
      text-align: center;
      transition: all 0.3s ease;

      &.active {
        border-color: #007aff;
        color: #007aff;
        background: rgba(0, 122, 255, 0.1);
      }

      &:active {
        transform: scale(0.95);
      }
    }
  }
}

.spec-quantity {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32rpx;

  .spec-quantity-label {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
  }

  .spec-quantity-control {
    display: flex;
    align-items: center;
    border: 1px solid #ddd;
    border-radius: 8rpx;
    overflow: hidden;

    .quantity-btn {
      width: 64rpx;
      height: 64rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      color: #333;
      background: #f8f8f8;
      transition: all 0.3s ease;

      &.disabled {
        color: #ccc;
        background: #f5f5f5;
      }

      &:not(.disabled):active {
        background: #e0e0e0;
      }
    }

    .quantity-input {
      width: 80rpx;
      height: 64rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      color: #333;
      border-left: 1px solid #ddd;
      border-right: 1px solid #ddd;
      background: #fff;
    }
  }
}

.spec-confirm {
  .spec-buttons {
    display: flex;
    gap: 16rpx;
  }

  .spec-confirm-btn {
    width: 100%;
    height: 88rpx;
    background: #007aff;
    color: white;
    border: none;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: 500;
    transition: all 0.3s ease;

    &.disabled {
      background: #ccc;
      opacity: 0.6;
    }

    &:not(.disabled):active {
      transform: scale(0.98);
    }
  }

  .spec-delete-btn {
    flex: 1;
    height: 88rpx;
    background: #ff4757;
    color: white;
    border: none;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: 500;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
      background: #e03e4a;
    }
  }

  .spec-buttons .spec-confirm-btn {
    flex: 1;
  }
}
</style>
